package com.zxjbyte.yiyi.framework.web.publisher;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zxjbyte.yiyi.framework.common.util.ServletXUtil;
import com.zxjbyte.yiyi.framework.common.util.AuthUtil;
import com.zxjbyte.yiyi.framework.web.event.ErrorLogAddEvent;
import com.zxjbyte.yiyi.module.system.domain.dto.log.ErrorLogAddDTO;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * 异常信息发送
 * @Author zhangxingjia
 * @Date 2023/3/17 21:31
 * @Version: 1.0
 */
public class ErrorLogPublisher {

    /**
     * 推送消息
     * @param ex
     */
    public static void publishEvent(Throwable ex) {
        ErrorLogAddDTO reqDto = new ErrorLogAddDTO();
        reqDto.setUserId(AuthUtil.getUserId());
        reqDto.setTenantId(AuthUtil.getTenantId());
        reqDto.setApplicationName(SpringUtil.getApplicationName());
        reqDto.setExceptionName(ex.getClass().getName());
        reqDto.setExceptionMessage(ExceptionUtil.getMessage(ex));
        reqDto.setExceptionRootCauseMessage(ExceptionUtil.getRootCauseMessage(ex));
        reqDto.setExceptionStackTrace(ExceptionUtil.stacktraceToString(ex, Integer.MAX_VALUE));
        StackTraceElement[] stackTraceElements = ex.getStackTrace();
        if(ArrayUtil.isNotEmpty(stackTraceElements)){
            StackTraceElement stackTraceElement = stackTraceElements[0];
            reqDto.setExceptionClassName(stackTraceElement.getClassName());
            reqDto.setExceptionFileName(stackTraceElement.getFileName());
            reqDto.setExceptionMethodName(stackTraceElement.getMethodName());
            reqDto.setExceptionLineNumber(stackTraceElement.getLineNumber());
        }
        HttpServletRequest request = ServletXUtil.getRequest();
        if(Objects.nonNull(request)){
            reqDto.setRequestUrl(request.getRequestURI());
            reqDto.setRequestParams(ServletXUtil.getRequestContent(request));
            reqDto.setRequestMethod(request.getMethod());
            reqDto.setUserAgent(ServletXUtil.getUserAgent(request));
            reqDto.setUserIp(ServletXUtil.getClientIP(request));
        }
        reqDto.setExceptionTime(new Date());
        String uidStr = AuthUtil.getUserIdAsStr();
        reqDto.setCreateUser(uidStr);
        reqDto.setUpdateUser(uidStr);
        SpringUtil.publishEvent(new ErrorLogAddEvent(reqDto));
    }
}
